package com.wjb.xietong.ota.task;

import java.io.File;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;
import com.wjb.xietong.R;
import com.wjb.xietong.control.AsyncImageLoader;
import com.wjb.xietong.control.WJBControl;
import com.wjb.xietong.datamanager.LoginUserDataManager;
import com.wjb.xietong.datamanager.WJBDataManager;
import com.wjb.xietong.ota.BaseOTA;
import com.wjb.xietong.ota.task.NotifyPersonPopWindow.NotifyPersonResultListener;
import com.wjb.xietong.server.IRequestResultListener;
import com.wjb.xietong.server.taskReply.TaskFileUploadParam;
import com.wjb.xietong.server.taskReply.TaskReplyParam;
import com.wjb.xietong.server.taskReply.TaskFileUploadService.ITaskFileUploadListener;
import com.wjb.xietong.server.taskReply.TaskReplyParam.FileInfo;
import com.wjb.xietong.server.taskdetail.GetTaskDetailParam;
import com.wjb.xietong.server.taskdetail.GetTaskDetailResponse;
import com.wjb.xietong.server.taskdetail.GetTaskDetailResponse.GetTaskDetailHeaderInfo;
import com.wjb.xietong.server.taskdetail.GetTaskDetailResponse.GetTaskDetailInfo;
import com.wjb.xietong.server.taskdetail.GetTaskDetailResponse.GetTaskDetailInfo.TaskDetailContentInfo;
import com.wjb.xietong.server.taskdetail.GetTaskDetailResponse.GetTaskDetailNotifyInfo;
import com.wjb.xietong.util.EnumDefine.Login_User_Info;
import com.wjb.xietong.util.IDs;
import com.wjb.xietong.view.CVCirclePictureView;
import com.wjb.xietong.view.CVMatchListView;
import com.wjb.xietong.view.SelectPicPopupWindow;

public class OTATaskDetail extends BaseOTA {
	private SelectPicPopupWindow popWindow = null;
	private ScrollView mScrollView = null;
	private CVMatchListView mCommentListView = null;
	private ListAdapter mAdapter = null;
	private List<GetTaskDetailInfo> taskDetailInfoList = new ArrayList<GetTaskDetailInfo>();
	private List<GetTaskDetailNotifyInfo> notifyInfoList = new ArrayList<GetTaskDetailNotifyInfo>();
	
	private ArrayList<GetTaskDetailNotifyInfo> noticeUsersList = new ArrayList<GetTaskDetailNotifyInfo>();
	private ArrayList<FileInfo> filesList = new ArrayList<FileInfo>();
	private int fileSize = 0;

	private boolean isComeFromNotice = false;
	private long taskId = 0l;
	private long companyId = 0l;
	private long projectId = 0l;

	private TextView txt_b1 = null;
	private TextView txt_b2 = null;
	private TextView txt_b3 = null;
	private TextView txt_b4 = null;
	private Button btn_notice = null;
	private TextView tvNotice = null;
	private Button btn_add_file = null;
	private TextView tvFileNames = null;
	private EditText edittext_message = null;
	private Button btn_submit_comment = null;
	
	private int curTaskTabIndex = 0;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		curTaskTabIndex = getIntent().getIntExtra("cur_tasktab_index", 0);
		isComeFromNotice = getIntent().getBooleanExtra("from_notice", false);
		taskId = getIntent().getLongExtra("taskId", 0l);
		companyId = getIntent().getLongExtra("companyId", 0l);
		projectId = getIntent().getLongExtra("projectId", 0l);

		setContentField(getLayoutInflater().inflate(R.layout.page_task_detail,
				null));
		if(curTaskTabIndex == 2){
			setTopBarAndAction(getString(R.string.STR_TASK_01),
					new OnClickListener() {

						@Override
						public void onClick(View arg0) {
							app_.getActManager().popActivity();
						}
					}, null);
		}else{
			setTopBarAndAction(getString(R.string.STR_TASK_01),
					new OnClickListener() {
	
						@Override
						public void onClick(View arg0) {
							app_.getActManager().popActivity();
						}
					}, new OnClickListener() {
	
						@Override
						public void onClick(View arg0) {
							popWindow = new SelectPicPopupWindow(
									OTATaskDetail.this, curTaskTabIndex == 1, onclick);
							// 显示窗口
							popWindow.showAtLocation(OTATaskDetail.this
									.findViewById(R.id.id_scrollview),
									Gravity.BOTTOM , 0,
									0); // 设置layout在PopupWindow中显示的位置
							hideInputMethod();
	
						}
					}, R.drawable.nav_title_more);
		}
	}

	@Override
	protected void findView(View v) {
		mScrollView = (ScrollView) v.findViewById(R.id.id_scrollview);

		mCommentListView = (CVMatchListView) v.findViewById(R.id.id_listView);
		txt_b1 = (TextView) v.findViewById(R.id.txt_b1);
		txt_b2 = (TextView) v.findViewById(R.id.txt_b2);
		txt_b3 = (TextView) v.findViewById(R.id.txt_b3);
		txt_b4 = (TextView) v.findViewById(R.id.txt_b4);
		mAdapter = new ListAdapter(this);
		mCommentListView.setAdapter(mAdapter);

		btn_add_file = (Button) v.findViewById(R.id.btn_add_file);

		mScrollView.post(new Runnable() {
			@Override
			public void run() {
				if (isComeFromNotice) {
					mScrollView.fullScroll(ScrollView.FOCUS_DOWN);
//					mScrollView.smoothScrollTo(0, mCommentListView.getBottom());
				} else {
					mScrollView.fullScroll(ScrollView.FOCUS_UP);
				}
			}
		});
		edittext_message = (EditText) v.findViewById(R.id.message);
//		if (isComeFromNotice) {//如果是通知页面跳转过来的则设置焦点事件
//			edittext_message.setFocusable(true);
//			edittext_message.setFocusableInTouchMode(true);
//		}
		btn_submit_comment = (Button) v.findViewById(R.id.btn_submit_comment);
		btn_notice = (Button) v.findViewById(R.id.btn_notice);
		tvNotice = (TextView) v.findViewById(R.id.tv_notice);
		tvFileNames = (TextView) v.findViewById(R.id.tv_file);
		requestTaskDetailInfo();
	}

	@Override
	protected void setOnClickEvent() {
		super.setOnClickEvent();
		btn_add_file.setOnClickListener(onclick);
		btn_submit_comment.setOnClickListener(onclick);
		btn_notice.setOnClickListener(onclick);
		edittext_message.setOnClickListener(onclick);
	}

	/**
	 * 隐藏软键盘
	 */
	private void hideInputMethod() {
		InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(OTATaskDetail.this.getCurrentFocus()
				.getWindowToken(), 0); // 强制隐藏键盘
	}

	// 为弹出窗口实现监听类
	private OnClickListener onclick = new OnClickListener() {
		@Override
		public void onClick(View view) {
			switch (view.getId()) {
			case R.id.message:
				break;
			case R.id.btn_add_file:
				openFile();
				break;
			case R.id.btn_submit_comment:
				final String comment = edittext_message.getText().toString();
				if (null == comment || "".equals(comment)) {
					Toast.makeText(OTATaskDetail.this, "请输入评论内容", Toast.LENGTH_LONG)
							.show();
				}else{
					submitTaskReply();
				}
				break;
			case R.id.btn_notice:
				NotifyPersonPopWindow notifyPersonPopWindow = new NotifyPersonPopWindow(OTATaskDetail.this);
				notifyPersonPopWindow.showPopWindow(view, new NotifyPersonResultListener() {
					
					@Override
					public void onResult(int index) {
						GetTaskDetailNotifyInfo noticeInfo = new GetTaskDetailNotifyInfo();
						noticeInfo.setUserId(notifyInfoList.get(index).getUserId());
						noticeInfo.setUsername((notifyInfoList.get(index).getUsername() + ""));
						
						boolean existSame = false;
						int sameIndex = -1; 
						final int OLD_SIZE =  noticeUsersList.size();
						for(int i = 0; i < OLD_SIZE; i++){
							if(noticeInfo.getUserId() == noticeUsersList.get(i).getUserId()){
								existSame = true;
								sameIndex = i;
							}
						}
						if(existSame){
							if(sameIndex != -1){
								noticeUsersList.remove(sameIndex);
							}
						}else{
							noticeUsersList.add(noticeInfo);
						}
						
						final int SIZE =  noticeUsersList.size();
						StringBuffer strBuf = new StringBuffer();
						for(int i = 0; i < SIZE; i++){
							strBuf.append(noticeUsersList.get(i).getUsername());
							if(i < SIZE - 1){
								strBuf.append("\n");
							}
						}
						tvNotice.setText(strBuf.toString());
					}
				}, notifyInfoList);
				break;
			case R.id.btn_delete:
				break;
			case R.id.btn_edit:
				break;
			case R.id.btn_finish_task:
				if(curTaskTabIndex == 1){//显示取消完成那个
					
				}else{//显示完成任务
					
				}
				break;
			case R.id.btn_cancel:
				if (null != popWindow) {
					popWindow.dismiss();
				}
				break;
			default:
				break;
			}
		}
	};

	/**
	 * 上传文件
	 */
	private void postUploadFile(final FileInfo tempFileInfo) {
		
		fileSize++;
		long uniqueID = Calendar.getInstance().getTimeInMillis();
		ITaskFileUploadListener listener = new ITaskFileUploadListener() {

			@Override
			public void requestSuccess(long requestUniqueID, String filePath) {
				FileInfo fileInfo = new FileInfo();
				fileInfo.setFileName(tempFileInfo.getFileName());
				fileInfo.setFilePath(filePath);
				fileInfo.setFileSize(tempFileInfo.getFileSize());
				fileInfo.setImageHeight(tempFileInfo.getImageHeight());
				fileInfo.setImageWidth(tempFileInfo.getImageWidth());
				filesList.add(fileInfo);
				
				final int SIZE =  filesList.size();
				StringBuffer strBuf = new StringBuffer();
				for(int i = 0; i < SIZE; i++){
					strBuf.append(filesList.get(i).getFileName());
					if(i < SIZE - 1){
						strBuf.append("\n");
					}
				}
				tvFileNames.setText(strBuf.toString());
			}

			@Override
			public void requestFaield(long requestUniqueID,
					String errCode, String errMsg) {
				Toast.makeText(OTATaskDetail.this, "文件" + tempFileInfo.getFileName() + "上传失败",
						Toast.LENGTH_LONG).show();
			}
		};
		TaskFileUploadParam param =  new TaskFileUploadParam();
		param.setCompanyId((Long)LoginUserDataManager.getLoginUserInfo(Login_User_Info.COM_ID));
		param.setUserId((Long)LoginUserDataManager.getLoginUserInfo(Login_User_Info.ID));
		param.setFilePath(tempFileInfo.getFilePath());
		WJBControl.requestUploadFile(uniqueID, param, listener);
	}
	
	/**
	* Description: 提交任务回复
	 */
	private void submitTaskReply(){
		if(fileSize == filesList.size()){
			showProgressDialog();
			final String comment = edittext_message.getText().toString();
			
			long uniqueID = Calendar.getInstance().getTimeInMillis();
			IRequestResultListener listener = new IRequestResultListener() {

				@Override
				public void requestSuccess(long requestUniqueID) {
					initLocalData();
					requestTaskDetailInfo();
				}

				@Override
				public void requestFaield(long requestUniqueID,
						String errCode, String errMsg) {
					initLocalData();
					hideProgressDialog();
					Toast.makeText(OTATaskDetail.this, errMsg,
							Toast.LENGTH_LONG).show();
				}
			};
			TaskReplyParam param =  new TaskReplyParam();
			param.setCompanyId((Long)LoginUserDataManager.getLoginUserInfo(Login_User_Info.COM_ID));
			param.setUserId((Long)LoginUserDataManager.getLoginUserInfo(Login_User_Info.ID));
			param.setContent(comment);
			param.setFileInfoList(filesList);
			
			ArrayList<String> noticeUserIDs = new ArrayList<String>();
			for(GetTaskDetailNotifyInfo info : noticeUsersList){
				noticeUserIDs.add(info.getUserId() + "");
			}
			param.setNotifyUserIDList(noticeUserIDs);
			param.setProjectId(projectId);
			param.setTaskId(taskId);
			WJBControl.requestReplyTask(uniqueID, param, listener);
		}else{
			Toast.makeText(OTATaskDetail.this, "等待附件上传完毕！",
							Toast.LENGTH_LONG).show();
		}
	}
	
	/**
	 * 初始化本地数据
	 */
	private void initLocalData(){
		this.fileSize = 0;
		this.filesList.clear();
		this.noticeUsersList.clear();
		tvFileNames.setText("");
		edittext_message.setText("");
	}

	/**
	 * 更新任务详细数据
	 */
	private void updateTaskDetailData() {
		GetTaskDetailResponse taskDetailResponse = WJBDataManager
				.getTaskDetailResponseInfo();
		GetTaskDetailHeaderInfo taskHeaderInfo = taskDetailResponse
				.getTaskHeaderInfo();
		if (null != taskHeaderInfo) {
			setTitleTitleBar("" + taskHeaderInfo.getTitle());
			txt_b1.setText("" + taskHeaderInfo.getTitle());
			txt_b2.setText("" + taskHeaderInfo.getProjectTitle());
			txt_b3.setText("" + taskHeaderInfo.getUsername());
			txt_b4.setText("" + taskHeaderInfo.getDueDate());
		} else {
			Toast.makeText(OTATaskDetail.this, "服务器异常，没有返回任务详细数据",
					Toast.LENGTH_LONG).show();
		}

		if (null != taskDetailResponse.getGetTaskInfoList()) {
			taskDetailInfoList = taskDetailResponse.getGetTaskInfoList();
			mAdapter.notifyDataSetChanged();
		}

		// 获取通知列表联系人
		notifyInfoList = taskDetailResponse.getGetTaskDetailNotifyInfoList();
	}

	/**
	 * 请求获取任务详细
	 */
	private void requestTaskDetailInfo() {
		showProgressDialog();
		GetTaskDetailParam param = new GetTaskDetailParam();
		param.setCompanyId(companyId);
		param.setProjectId(projectId);
		param.setTaskId(taskId);
		param.setUserId((Long) LoginUserDataManager
				.getLoginUserInfo(Login_User_Info.ID));
		param.setPageIndex(0);
		param.setPageSize(10);
		WJBControl.requestGetDetailTask(Calendar.getInstance()
				.getTimeInMillis(), param, new IRequestResultListener() {

			@Override
			public void requestSuccess(long requestUniqueID) {
				hideProgressDialog();
				updateTaskDetailData();
			}

			@Override
			public void requestFaield(long requestUniqueID, String errCode,
					String errMsg) {
				hideProgressDialog();
				Toast.makeText(
						OTATaskDetail.this,
						(null == errMsg || "".equals(errMsg)) ? "获取任务详情失败，请稍后重试"
								: errMsg, Toast.LENGTH_LONG).show();
			}
		});
	}

	private void openFile() {
		Intent intent = new Intent();
		intent.setType("*/*");
		/* 使用Intent.ACTION_GET_CONTENT这个Action */
		intent.setAction(Intent.ACTION_GET_CONTENT);
		/* 取得文件后返回此页面 */
		startActivityForResult(intent, 1);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == 1) {
			if (resultCode == RESULT_OK) {
				Uri uri = data.getData();
//				String file = uri.getScheme();
				if ("file".equals(uri.getScheme())) {
					FileInfo fileInfo = new FileInfo();
					fileInfo.setFilePath(uri.getPath()); // 文件路径
					fileInfo.setFileSize(new File(uri.getPath()).length()); // 文件大小
					fileInfo.setFileName(uri.getLastPathSegment());// 文件名
					postUploadFile(fileInfo);
				} else if ("content".equals(uri.getScheme())) {
					Cursor cursor = getContentResolver().query(uri, null, null,
							null, null);
					if(null != cursor && cursor.moveToFirst()){
						FileInfo fileInfo = new FileInfo();
						fileInfo.setFilePath(cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA))); // 文件路径
						fileInfo.setFileSize(cursor.getLong(cursor.getColumnIndex(MediaStore.Images.Media.SIZE))); // 文件大小
						fileInfo.setFileName(cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DISPLAY_NAME)));// 文件名
						fileInfo.setImageHeight(cursor.getInt(cursor.getColumnIndex(MediaStore.Images.Media.HEIGHT)));
						fileInfo.setImageWidth(cursor.getInt(cursor.getColumnIndex(MediaStore.Images.Media.WIDTH)));
						postUploadFile(fileInfo);
					}else{
						Toast.makeText(OTATaskDetail.this, "读取文件失败，请重试~", Toast.LENGTH_LONG).show();
					}
				}

				/**
				 * do something
				 */
			}
		}
	}

	public class ListAdapter extends BaseAdapter {
		private LayoutInflater mInflater;

		public ListAdapter(Context context) {
			this.mInflater = LayoutInflater.from(context);
		}

		@Override
		public int getCount() {
			return taskDetailInfoList.size();
		}

		@Override
		public Object getItem(int arg0) {
			return taskDetailInfoList.get(arg0);
		}

		@Override
		public long getItemId(int arg0) {
			return arg0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder;
			if (convertView == null) {
				convertView = mInflater.inflate(
						R.layout.item_task_comment_list, null);
				holder = new ViewHolder();
				/* 得到各个控件的对象 */
				holder.icon = (CVCirclePictureView) convertView
						.findViewById(R.id.head_view);
				holder.name = (TextView) convertView.findViewById(R.id.name);
				holder.date = (TextView) convertView.findViewById(R.id.date);
				holder.llDetail = (LinearLayout) convertView
						.findViewById(R.id.id_item_txt_img_vector);

				convertView.setTag(holder); // 绑定ViewHolder对象
			} else {
				holder = (ViewHolder) convertView.getTag(); // 取出ViewHolder对象
			}

			holder.icon.setImageResource(R.drawable.taskdetail_temp_flag);
			holder.name.setText(""
					+ taskDetailInfoList.get(position).getCreate_username());
			holder.date.setText(""
					+ taskDetailInfoList.get(position).getGmt_create());

			holder.llDetail.removeAllViews();
			List<TaskDetailContentInfo> contentInfoList = taskDetailInfoList
					.get(position).getContentInfoList();
			for (TaskDetailContentInfo contentInfo : contentInfoList) {
				if (IDs.CONTENT_TYPE_TEXT.equals(contentInfo.getType())) {// 文字
					TextView txt = new TextView(OTATaskDetail.this);
					txt.setText("" + contentInfo.getText());
					holder.llDetail.addView(txt, new LinearLayout.LayoutParams(
							LinearLayout.LayoutParams.MATCH_PARENT,
							LinearLayout.LayoutParams.WRAP_CONTENT));
				} else if (IDs.CONTENT_TYPE_IMAGE.equals(contentInfo.getType())) {// 图片
					ImageView img = new ImageView(OTATaskDetail.this);
					img.setClickable(true);
					img.setScaleType(ScaleType.FIT_START);
					AsyncImageLoader.Instance()
							.loadDrawableForImageView(
									contentInfo.getImageLink(), img,
									R.drawable.trans);
					holder.llDetail.addView(img, new LinearLayout.LayoutParams(
							LinearLayout.LayoutParams.MATCH_PARENT,
							LinearLayout.LayoutParams.WRAP_CONTENT));
				}
			}

			return convertView;
		}

		/* 存放控件 的ViewHolder */
		public final class ViewHolder {
			public CVCirclePictureView icon;
			public TextView name;
			public TextView date;
			public LinearLayout llDetail;
		}
	}
}
